package com.itheima.web;

import com.itheima.pojo.NewShoppingCart;
import com.itheima.pojo.ShoppingCart;
import com.itheima.pojo.User;
import com.itheima.service.NewShoppingCartService;
import com.itheima.service.ShoppingCartService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/addToShoppingCartServlet")
public class AddToShoppingCartServlet extends HttpServlet {
    private ShoppingCartService service = new ShoppingCartService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Integer itemId = Integer.valueOf(request.getParameter("id"));

        // 通过session获取user对象
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");

        Integer buyerId = user.getId();

        List<ShoppingCart> shoppingCartGoods = service.selectByBuyerIdAndItemId(itemId, buyerId);
        if (!shoppingCartGoods.isEmpty()) {
            Integer itemQuantity = shoppingCartGoods.get(0).getItemQuantity();
            itemQuantity += 1;
            service.updateItemQuantity(itemId, buyerId, itemQuantity);
        }
        else {
            service.add(itemId, buyerId, 1);
        }

//        // 判断购物车中是否有两个及以上的小米手机，生成赠品
//        List<ShoppingCart> xiaomiPhones = service.selectByBuyerIdAndItemId(3, buyerId);
//        if (!xiaomiPhones.isEmpty()) {
//            Integer itemQuantity = xiaomiPhones.get(0).getItemQuantity();
//            Integer giftQuantity = itemQuantity / 2;
//            if (giftQuantity > 0) {
//                List<ShoppingCart> gifts = service.selectByBuyerIdAndItemId(8, buyerId);
//                // 如果购物车中还没有赠品
//                if (gifts.isEmpty()) {
//                    service.add(8, buyerId, giftQuantity);
//                }
//                // 如果购物车中已经有赠品
//                else {
//                    service.updateItemQuantity(8, buyerId, giftQuantity);
//                }
//            }
//        }

        String id = itemId.toString();
        String url = "itemDetailServlet?id=" + id;
        response.sendRedirect(url);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
